package chapter04;

import java.util.Scanner;

//
public class test03 {
    public static void main(String[] args) {
        Arraystack arraystack = new Arraystack(4);
        String key="";
        boolean loop=true;
        Scanner scanner = new Scanner(System.in);
        while (loop){
            System.out.println("show:表示显示栈");
            System.out.println("exit:退出程序");
            System.out.println("push:表示添加数据到栈（入栈）");
            System.out.println("pop:表示从栈取出数据（出栈）"  );
            System.out.println("输入");
            key=scanner.next();
            switch (key){
                case"show":
                    arraystack.list();
                break;
                case "push":
                    System.out.println("输入一个数");
                    int value=scanner.nextInt();
                    arraystack.push(value);
                    break;
                case "pop":
                    try {
                        int res=arraystack.pop();
                        System.out.println("出栈的数据是:"+res);
                    }catch (Exception e){
                        System.out.println(e.getMessage());
                    }
                    break;
                case "exit":scanner.close();
                loop=false;
                break;
            }
        }
    }
}
//创建一个栈
class Arraystack{
    private int maxSize;//栈的大小
    private int[] stack;
    private int top=-1;//

    public Arraystack(int maxSize) {
        this.maxSize = maxSize;
        stack=new int[this.maxSize];

    }
    public boolean isFull(){
        return  top==maxSize-1;
    }
    public boolean isEmpty(){
        return top==-1;

    }
    public void push(int value){
        //先判断栈是否满
        if(isFull()){
            System.out.println("栈满");
            return;
        }
        top++;
        stack[top]=value;

    }
    public int pop(){
        //判断栈是否为空
        if(isEmpty()){
            throw new RuntimeException("栈空");

        }
        int value=stack[top];
        top--;
        return  value;
    }
    //显示栈的情况，遍历栈，遍历时，需要从栈顶开始显示数据
    public void list(){
        if(isEmpty()){
            System.out.println("栈空");
            return;
        }
        for (int i = top; i >=0 ; i--) {
            System.out.println("stack["+i+"]="+stack[i]);
        }
    }


}

